// TypeScript file
/**
 * 网络管理类
 */
class NetMgr extends egret.DisplayObject {

    private socket: egret.WebSocket = new egret.WebSocket();
    static net: NetMgr;

    constructor() {
        super();

    }
    public static GetInstance(): NetMgr {
        if (this.net == null)
            this.net = new NetMgr();
        return this.net;
    }

    public StartSocket(serverip: string, port: number): void {
        if (this.socket.connected) return;
        this.socket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
        this.socket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
        this.socket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.IOError, this);
        this.socket.addEventListener(egret.Event.CLOSE, this.Close, this);
        this.socket.connect(serverip, port)


    }

    public GetStatus(): boolean {
        return this.socket.connected;
    }



    onReceiveMessage(): void {
        console.log("接收到消息:");
        var msg = this.socket.readUTF();
        console.log(msg);

        let protocol: Protocol<any> = JSON.parse(msg);
        // if (protocol.cmd) {
        try {
            let event = new NetEvent(NetEvent.Net);
            event.cmd = protocol.cmd;
            event.data = protocol;
            this.dispatchEvent(event)
        } catch (error) {
            console.error("网络事件:" + protocol.cmd + "-处理错误")
        }
    }

    Close(): void {
        console.log("连接关闭")

    }

    onSocketOpen(): void {

        console.log("网络连接成功");

    }

    IOError(): void {

        console.log("网络连接断开")


    }

    public Emit<T>(cmd: string, data: T): void {
        if (this.socket.connected) {
            let protocol = new Protocol<T>();
            protocol.cmd = cmd;
            protocol.data = data;
            this.socket.writeUTF(JSON.stringify(protocol));
        }

    }


}